package com.wl.shop.web;

import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springside.modules.web.Servlets;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Lists;
import com.wl.shop.entity.Dict;
import com.wl.shop.model.DataTableResult;
import com.wl.shop.model.RestResponse;
import com.wl.shop.utils.Constants;
import com.wl.shop.utils.StringUtils;

@Controller
@RequestMapping("${adminPath}/dict")
public class DictController extends BaseController {
	
	@RequestMapping(value = {"list",""},method = RequestMethod.GET)
	public String list(){
		return "sys/dict/list";
	}
	
	@RequestMapping(value = "list",method = RequestMethod.POST)
	@ResponseBody
	public DataTableResult list(String aodata,ServletRequest request){
		logger.info("设置datatable的值",aodata);
		Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
		String description = (String)searchParams.get("description");
		String lable  = (String)searchParams.get("label");
		String type   = (String)searchParams.get("type");
		Map<String,Object>	map =Constants.convertToMap(aodata);
		int echo = (Integer) map.get("sEcho");
		int start = (Integer)map.get("iDisplayStart");
		int pageSize = (Integer)map.get("iDisplayLength");
		int pageNum = start/pageSize==0?1:(start/pageSize+1);
		pageSize=pageSize>0?pageSize:10;
		DataTableResult result = new DataTableResult();
		result.setSEcho(echo);
		EntityWrapper<Dict> wrapper = new EntityWrapper<Dict>();
		wrapper.eq("is_del", false);
		wrapper.orderBy("type,create_date,sort");
		//如果描述不为空
		if(StringUtils.isNotBlank(description)){
			wrapper.like("description", description);
		}else{
			searchParams.remove("description");
		}
		//如果标签不为空
		if(StringUtils.isNotBlank(lable)){
			wrapper.eq("lable", lable);
		}else{
			searchParams.remove("lable");
		}
		//如果类型不为空
		if(StringUtils.isNotBlank(type)){
			wrapper.eq("type", type);
		}else{
			searchParams.remove("type");
		}
		
		Page<Dict> pageData = dictService.selectPage(new Page<Dict>(pageNum,pageSize), wrapper);
		result.setAaData(pageData.getRecords());
		result.setITotalRecords(pageData.getTotal());
		result.setITotalDisplayRecords(pageData.getTotal());
		if(!searchParams.isEmpty()){
			result.setSColumns(Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
		}
		return result;
	}
	
	@RequestMapping(value = "add",method = RequestMethod.GET)
	public String add(@RequestParam(value = "id",required=false) String id,Model model){
		if(StringUtils.isNotBlank(id)){
			Dict dict = dictService.selectById(id);
			model.addAttribute("dict", dict);
		}
		return "sys/dict/add";
	}
	
	@RequestMapping(value = "add",method = RequestMethod.POST)
	@ResponseBody
	public RestResponse add(@RequestBody Dict dict){
		if(StringUtils.isBlank(dict.getLabel())){
			return RestResponse.failure("标签不能为空");
		}
		if(StringUtils.isBlank(dict.getType())){
			return RestResponse.failure("类型不能为空");
		}
		if(StringUtils.isBlank(dict.getDescription())){
			return RestResponse.failure("描述不能为空");
		}
		if(StringUtils.isBlank(dict.getValue())){
			return RestResponse.failure("标签值不能为空");
		}
		if(dictService.isSameData(dict)){
			return RestResponse.failure("数据重复");
		}
		dict.setSort(dictService.getMaxSort(dict.getType())+10);
		dictService.saveOrUpdate(dict);
		return RestResponse.success();
	}
	
	@RequestMapping(value="edit",method = RequestMethod.GET)
	public String edit(@RequestParam(value = "id",required = false)String id,Model model){
		if(StringUtils.isBlank(id)){
			return "redirect:${adminPath}/dict";
		}
		Dict dict = dictService.selectById(id);
		model.addAttribute("dict", dict);
		return "sys/dict/edit";
	}
	
	@RequestMapping(value="edit",method = RequestMethod.POST)
	@ResponseBody
	public RestResponse edit(@RequestBody Dict dict){
		if(StringUtils.isBlank(dict.getId())){
			return RestResponse.failure("字典ID不能为空");
		}
		if(StringUtils.isBlank(dict.getLabel())){
			return RestResponse.failure("标签不能为空");
		}
		if(StringUtils.isBlank(dict.getType())){
			return RestResponse.failure("类型不能为空");
		}
		if(StringUtils.isBlank(dict.getDescription())){
			return RestResponse.failure("描述不能为空");
		}
		if(StringUtils.isBlank(dict.getValue())){
			return RestResponse.failure("标签值不能为空");
		}
		Dict old = dictService.selectById(dict.getId());
		if(!old.getType().equals(dict.getType())){
			dict.setSort(dictService.getMaxSort(dict.getType())+10);
		}
		dictService.saveOrUpdate(dict);
		return RestResponse.success();
	}
	
	@RequestMapping(value="delete",method = RequestMethod.POST)
	@ResponseBody
	public RestResponse delete(@RequestParam(value = "ids[]",required = false) List<String> ids){
		if(ids == null || ids.size()==0){
			return RestResponse.failure("未选择任何字典");
		}
		List<Dict> dicts = Lists.newArrayList();
		for (String id : ids) {
			Dict dict = new Dict();
			dict.setId(id);
			dict.setIsDel(true);
			dict.preUpdate();
			dicts.add(dict);
		}
		dictService.updateBatchById(dicts);
		return RestResponse.success();
	}
}
